package com.demo;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.log4j.Logger;
import org.apache.log4j.varia.NullAppender;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.netflix.config.ConfigurationManager;
import com.demo.gateway.service.impl.ScheduleJobService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author: demo
 * @date: 2020年6月10日
 * @Document : 网关服务项目
 */
@Slf4j
@SpringBootApplication
@ComponentScan(basePackages = { "com.demo" })
@MapperScan({ "com.demo" })
@EnableScheduling
@EnableHystrix
public class DemoGatewayApplication implements CommandLineRunner {
	@Value("${server.port}")
	private String port;

	@Autowired
	private ScheduleJobService scheduleJobService;

	public static void main(String[] args) {
		SpringApplication.run(DemoGatewayApplication.class, args);
	}

	@Override
	public void run(String... arg0) throws Exception {
		ignoreLog4jWarnInfo();
		log.info("{} 启动完成 !  ServerUrl ==>http://{}:{}/", DemoGatewayApplication.class.getSimpleName(), getHost(), port);
		startQuartzJobs();
		
		AbstractConfiguration config = ConfigurationManager.getConfigInstance();
		String defaultHystrixKey = (String) config.getProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds");
		log.info("defaultHystrixKey==>{}",defaultHystrixKey);
	}

	/**
	 * 关闭log4j的警告输出
	 */
	public void ignoreLog4jWarnInfo() {
		Logger.getRootLogger().addAppender(new NullAppender());
	}

	/**
	 * 开启定时任务
	 */
	public void startQuartzJobs() {
		scheduleJobService.refreshJobs();
	}

	/**
	 * host信息
	 * 
	 * @return
	 */
	public String getHost() {
		try {
			Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					InetAddress ip = (InetAddress) addresses.nextElement();
					// loopback地址即本机地址，IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
					if (ip != null && ip instanceof Inet4Address && !ip.isLoopbackAddress()
							&& ip.getHostAddress().indexOf(":") == -1) {
						return ip.getHostAddress();
					}
				}
			}
		} catch (Exception e) {
			log.error("获取host地址异常==>", e.getMessage());
		}
		return "localhost";
	}
}
